package com.shen.langchain4j.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisChatMemoryStore implements ChatMemoryStore {
    public static final String CHAT_MEMORY_STORE_PREFIX = "CHAT_MEMORY:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 实现通过内存ID从持久化存储中获取所有消息
     * @param memoryId The ID of the chat memory.
     * @return 消息集合
     */
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String messageValue = redisTemplate.opsForValue().get(CHAT_MEMORY_STORE_PREFIX + memoryId);
        return ChatMessageDeserializer.messagesFromJson(messageValue);
    }

    /**
     * 实现通过内存ID更新持久化存储中的所有消息
     * @param memoryId The ID of the chat memory.
     * @param messages List of messages for the specified chat memory, that represent the current state of the {@link ChatMemory}.
     *                 Can be serialized to JSON using {@link ChatMessageSerializer}.
     */
    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        redisTemplate.opsForValue().set(CHAT_MEMORY_STORE_PREFIX + memoryId,
                ChatMessageSerializer.messagesToJson(messages));
    }

    /**
     * 实现通过内存ID删除持久化存储中的所有消息
     * @param memoryId The ID of the chat memory.
     */
    @Override
    public void deleteMessages(Object memoryId) {
        redisTemplate.delete(CHAT_MEMORY_STORE_PREFIX + memoryId);
    }
}
